<?php

namespace App\Http\Controllers\Basic;


use App\Models\SmsCode;
use App\Models\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Mews\Captcha\Facades\Captcha;
use App\Libs\Sms;

class SmsController extends Controller
{
    //

    public function create(Request $request)
    {
        $rules = [
            //'captcha_code' => 'required|captcha',
            'phone' => 'required|is_phone',
        ];
        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        $phone = $request->input('phone');
        $ip = $request->getClientIp();

        $node = new SmsCode();
        $code = $node->getVerifyCode($phone, $ip);

        if($code === false)
        {
            $this->setStatus(20001);
            $this->setMsg('当日获取验证码超5次，请明天再试');
            return $this->response();
        }

        $sms = new Sms();
        $ret = $sms->sendTemplateSMS($phone, array($code, '五分钟'),209261);

        if($ret->statusCode !== '000000')
        {
            $this->setStatus(30001);
            $this->setMsg($ret->statusMsg);
        }
        return $this->response();
    }

    public function nocaptcha(Request $request)
    {
        $rules = [
            'phone' => 'required|is_phone',
        ];
        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        $phone = $request->input('phone');
        $ip = $request->getClientIp();

        $node = new SmsCode();
        $code = $node->getVerifyCode($phone, $ip);

        if($code === false)
        {
            $this->setStatus(20001);
            $this->setMsg('当日获取验证码超5次，请明天再试');
            return $this->response();
        }

        //$isUser = User::where('phone', $phone)->count();
        //
        //if($isUser == 0)
        //{
        //    $this->setStatus(10000);
        //    $this->setMsg('您的手机还未注册');
        //    return $this->response();
        //}

        $sms = new Sms();
        $ret = $sms->sendTemplateSMS($phone, array($code, '五分钟'),209261);

        if($ret->statusCode !== '000000')
        {
            $this->setStatus(30001);
            $this->setMsg($ret->statusMsg);
        }
        return $this->response();
    }


}
